import React, { useState, useEffect } from 'react';
import { Form, Input, Select, Button, Table, Card, Row, Col, message, Divider, Typography, Space, Modal, InputNumber } from 'antd';
import { UserOutlined, PhoneOutlined, HomeOutlined, ShoppingCartOutlined, UploadOutlined, SaveOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import './OnlineOrdering.css';
import chinaAreaData from './chinaAreaData';

const { Option } = Select;
const { Title, Text } = Typography;

// 省份数据
const provinces = chinaAreaData.provinces;

// 城市数据，根据省份选择显示
const cities = chinaAreaData.cities;

// 区县数据，根据城市选择显示
const districts = chinaAreaData.districts;

interface AreaItem {
  value: string;
  label: string;
}

interface GoodsItem {
  key: string;
  name: string;
  description: string;
  specifications: string;
  quantity: number;
  price: number;
}

interface OrderingFormData {
  senderName: string;
  senderPhone: string;
  senderAddress: string;
  receiverName: string;
  receiverPhone: string;
  receiverProvince: string;
  receiverCity: string;
  receiverDistrict: string;
  receiverDetailAddress: string;
  receiverIdCard: string;
  weight: string;
  insurance: string;
  insuranceFee: string;
  length: string;
  width: string;
  height: string;
}

const OnlineOrdering: React.FC = () => {
  const [form] = Form.useForm();
  const [goodsForm] = Form.useForm(); // 用于物品添加的表单
  const [goodsList, setGoodsList] = useState<GoodsItem[]>([]);
  const [totalDeclaredValue, setTotalDeclaredValue] = useState<string>('0.00');
  const [totalInsurance, setTotalInsurance] = useState<string>('0.00');
  const [totalActualValue, setTotalActualValue] = useState<string>('0.00');
  const [volumeWeight, setVolumeWeight] = useState<number>(0);
  const [savedData, setSavedData] = useState<OrderingFormData | null>(null);
  const [savedGoods, setSavedGoods] = useState<GoodsItem[]>([]);
  const [saveStatus, setSaveStatus] = useState({
    sender: false,
    receiver: false
  });
  const [addGoodsModalVisible, setAddGoodsModalVisible] = useState(false);
  
  // 地址三级联动状态
  const [selectedProvince, setSelectedProvince] = useState<string>('');
  const [selectedCity, setSelectedCity] = useState<string>('');
  const [availableCities, setAvailableCities] = useState<{value: string, label: string}[]>([]);
  const [availableDistricts, setAvailableDistricts] = useState<{value: string, label: string}[]>([]);

  // 初始化一些示例数据
  useEffect(() => {
    // 初始化为空列表，让用户自行添加物品
    setGoodsList([]);
  }, []);

  // 处理省份变化
  const handleProvinceChange = (value: string) => {
    console.log('Selected province:', value);
    setSelectedProvince(value);
    setSelectedCity('');
    form.setFieldsValue({ receiverCity: undefined, receiverDistrict: undefined });
    
    // 更新可选城市列表
    if (value && cities[value]) {
      console.log('Available cities:', cities[value]);
      setAvailableCities(cities[value]);
    } else {
      console.log('No cities found for province:', value);
      setAvailableCities([]);
    }
    setAvailableDistricts([]);
  };

  // 处理城市变化
  const handleCityChange = (value: string) => {
    console.log('Selected city:', value);
    setSelectedCity(value);
    form.setFieldsValue({ receiverDistrict: undefined });
    
    // 更新可选区县列表
    const cityKey = value; // 使用城市的value作为key
    
    if (cityKey && districts[cityKey]) {
      console.log('Available districts for city key:', cityKey, districts[cityKey]);
      setAvailableDistricts(districts[cityKey]);
    } else {
      // 如果没有找到对应城市的区县数据，则使用默认区县数据
      const defaultDistricts = [
        { value: 'district1', label: '第一区' },
        { value: 'district2', label: '第二区' },
        { value: 'district3', label: '第三区' },
        { value: 'district4', label: '第四区' },
        { value: 'district5', label: '第五区' }
      ];
      console.log('Using default districts for city:', value);
      setAvailableDistricts(defaultDistricts);
    }
  };

  const columns = [
    {
      title: '选择',
      dataIndex: 'action',
      key: 'action',
      width: 80,
      render: () => <Button type="primary" size="small" className="select-btn">选择</Button>
    },
    {
      title: '货物名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
    },
    {
      title: '物品描述',
      dataIndex: 'description',
      key: 'description',
      width: 150,
    },
    {
      title: '物品名称',
      dataIndex: 'goodsName',
      key: 'goodsName',
      width: 180,
      render: (_: any, record: GoodsItem) => record.name // 实际显示name字段
    },
    {
      title: '规格码',
      dataIndex: 'specifications',
      key: 'specifications',
      width: 140,
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 100,
    },
    {
      title: '申报单价(元)',
      dataIndex: 'price',
      key: 'price',
      width: 120,
    },
    {
      title: '操作',
      key: 'operation',
      width: 120,
      render: (_: any, record: GoodsItem) => (
        <Space>
          <Button type="primary" icon={<PlusOutlined />} size="small" className="add-btn" onClick={showAddGoodsModal} />
          <Button type="primary" danger icon={<DeleteOutlined />} size="small" className="delete-btn" onClick={() => handleDeleteGoods(record.key)} />
        </Space>
      ),
    },
  ];

  const handleSubmit = (values: any) => {
    console.log('表单提交值:', values);
    setSavedData(values);
    setSavedGoods([...goodsList]);
    message.success('订单提交成功');
  };

  // 显示添加物品表单
  const showAddGoodsModal = () => {
    goodsForm.resetFields();
    setAddGoodsModalVisible(true);
  };

  // 关闭添加物品表单
  const handleAddGoodsCancel = () => {
    setAddGoodsModalVisible(false);
  };

  // 处理添加物品表单提交
  const handleAddGoodsSubmit = () => {
    goodsForm.validateFields().then(values => {
      const newGoods = {
        key: Date.now().toString(),
        name: values.name,
        description: values.description,
        specifications: values.specifications,
        quantity: values.quantity,
        price: values.price
      };
      const updatedList = [...goodsList, newGoods];
      setGoodsList(updatedList);
      updateTotals(updatedList);
      setAddGoodsModalVisible(false);
      message.success('物品添加成功');
    }).catch(info => {
      console.log('验证失败:', info);
    });
  };

  // 保留原来的添加空物品的方法，但不再使用
  const handleAddGoods = () => {
    showAddGoodsModal();
  };

  const handleDeleteGoods = (key: string) => {
    const newList = goodsList.filter(item => item.key !== key);
    setGoodsList(newList);
    updateTotals(newList);
  };

  const updateTotals = (goods: GoodsItem[]) => {
    const declaredValue = goods.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2);
    setTotalDeclaredValue(declaredValue);
    setTotalInsurance('0.00');
    setTotalActualValue('0.00');
  };

  const handleSaveSender = () => {
    const senderValues = form.getFieldsValue(['senderName', 'senderPhone', 'senderAddress']);
    if (senderValues.senderName && senderValues.senderPhone) {
      setSaveStatus({...saveStatus, sender: true});
      message.success('发货人信息保存成功');
    } else {
      message.error('请填写必填信息');
    }
  };

  const handleSaveReceiver = () => {
    const receiverValues = form.getFieldsValue(['receiverName', 'receiverPhone', 'receiverProvince', 'receiverCity', 'receiverDistrict']);
    if (receiverValues.receiverName && receiverValues.receiverPhone && receiverValues.receiverProvince) {
      setSaveStatus({...saveStatus, receiver: true});
      message.success('收货人信息保存成功');
    } else {
      message.error('请填写必填信息');
    }
  };

  const calculateVolumeWeight = () => {
    const length = parseFloat(form.getFieldValue('length') || '0');
    const width = parseFloat(form.getFieldValue('width') || '0');
    const height = parseFloat(form.getFieldValue('height') || '0');
    
    if (length && width && height) {
      const volume = (length * width * height / 6000).toFixed(2);
      setVolumeWeight(parseFloat(volume));
    }
  };

  return (
    <div className="online-ordering-container">
      <Title level={2} style={{ marginBottom: 24 }}>在线下单系统</Title>
      
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        className="ordering-form"
        initialValues={{
          senderName: '李先生',
          senderPhone: '15299367217',
          senderAddress: '山东青岛',
          insurance: 'none'
        }}
      >
        <Card 
          title={
            <Space>
              <UserOutlined /> 发货人信息
            </Space>
          } 
          className="form-card" 
          extra={<div className="save-btn">
            <Button type="primary" onClick={handleSaveSender} icon={<SaveOutlined />}>保存</Button>
            {saveStatus.sender && <span className="check-icon">✓</span>}
          </div>}
        >
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item label="姓名" name="senderName" rules={[{ required: true, message: '请输入姓名' }]}>
                <Input placeholder="李先生" prefix={<UserOutlined />} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="电话" name="senderPhone" rules={[{ required: true, message: '请输入电话' }]}>
                <Input placeholder="15299367217" prefix={<PhoneOutlined />} />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={16}>
              <Form.Item label="地址" name="senderAddress">
                <Input placeholder="山东青岛" prefix={<HomeOutlined />} />
              </Form.Item>
            </Col>
          </Row>
        </Card>

        <Card 
          title={
            <Space>
              <UserOutlined /> 收货人信息
            </Space>
          } 
          className="form-card" 
          extra={<div className="save-btn">
            <Button type="primary" onClick={handleSaveReceiver} icon={<SaveOutlined />}>保存</Button>
            {saveStatus.receiver && <span className="check-icon">✓</span>}
          </div>}
        >
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item label="姓名" name="receiverName" rules={[{ required: true, message: '请输入姓名' }]}>
                <Input prefix={<UserOutlined />} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="电话" name="receiverPhone" rules={[{ required: true, message: '请输入电话' }]}>
                <Input prefix={<PhoneOutlined />} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item label="地址" name="receiverProvince" rules={[{ required: true, message: '请选择省份' }]}>
                <Select 
                  placeholder="请选择省份"
                  onChange={handleProvinceChange}
                >
                  {provinces.map((province: AreaItem) => (
                    <Option key={province.value} value={province.value}>{province.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="receiverCity">
                <Select 
                  placeholder="请选择城市" 
                  disabled={!selectedProvince}
                  onChange={handleCityChange}
                >
                  {availableCities.map((city: AreaItem) => (
                    <Option key={city.value} value={city.value}>{city.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="receiverDistrict">
                <Select 
                  placeholder="请选择区县"
                  disabled={!selectedCity}
                >
                  {availableDistricts.map((district: AreaItem) => (
                    <Option key={district.value} value={district.value}>{district.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={16}>
              <Form.Item label="详细地址" name="receiverDetailAddress">
                <Input prefix={<HomeOutlined />} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="证件号" name="receiverIdCard">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item label="身份正面">
                <Button type="primary" icon={<UploadOutlined />}>文件上传</Button>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="身份反面">
                <Button type="primary" icon={<UploadOutlined />}>文件上传</Button>
              </Form.Item>
            </Col>
          </Row>
        </Card>

        <Card 
          title={
            <Space>
              <ShoppingCartOutlined /> 物品信息
            </Space>
          } 
          className="form-card" 
          extra={<Button type="primary" icon={<PlusOutlined />} onClick={showAddGoodsModal}>添加物品</Button>}
        >
          {goodsList.length > 0 ? (
            <Table 
              columns={columns}
              dataSource={goodsList}
              pagination={false}
              bordered
              className="goods-table"
              scroll={{ x: 'max-content' }}
            />
          ) : (
            <div className="empty-goods-list">
              <div className="empty-placeholder">
                <ShoppingCartOutlined style={{ fontSize: '48px', color: '#bfbfbf' }} />
                <p>暂无物品信息，请点击"添加物品"按钮添加</p>
                <Button type="primary" icon={<PlusOutlined />} onClick={showAddGoodsModal}>
                  添加物品
                </Button>
              </div>
            </div>
          )}
          <div className="total-info">
            <span>申报总价值: {totalDeclaredValue}元</span>
            <span>税费: {totalInsurance}元</span>
            <span>实收税费: {totalActualValue}元</span>
          </div>
          
          <Divider orientation="left">附加信息</Divider>
          
          <Row gutter={24} className="additional-info">
            <Col span={8}>
              <Form.Item label="重量(KG)" name="weight">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="保险" name="insurance">
                <Select defaultValue="无保险">
                  <Option value="none">无保险</Option>
                  <Option value="basic">基础保险</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="保费(元)" name="insuranceFee">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={24} className="size-info">
            <Col span={24}>
              <div className="size-container">
                <Text strong>体积值：</Text>
                <Form.Item name="length" noStyle>
                  <Input addonBefore="长" addonAfter="CM" style={{ width: 120 }} onChange={calculateVolumeWeight} />
                </Form.Item>
                <Form.Item name="width" noStyle>
                  <Input addonBefore="宽" addonAfter="CM" style={{ width: 120 }} onChange={calculateVolumeWeight} />
                </Form.Item>
                <Form.Item name="height" noStyle>
                  <Input addonBefore="高" addonAfter="CM" style={{ width: 120 }} onChange={calculateVolumeWeight} />
                </Form.Item>
                <Text strong>= 体积重：{volumeWeight}</Text>
              </div>
            </Col>
          </Row>

          <Form.Item>
            <Button type="primary" htmlType="submit" className="submit-btn" size="large">
              提交订单
            </Button>
          </Form.Item>
        </Card>
      </Form>

      {savedData && (
        <Card 
          title={<span><ShoppingCartOutlined /> 已保存的订单信息</span>} 
          className="form-card saved-order-card"
        >
          <div>
            <h3>发货人信息</h3>
            <p><strong>姓名:</strong> {savedData.senderName}</p>
            <p><strong>电话:</strong> {savedData.senderPhone}</p>
            <p><strong>地址:</strong> {savedData.senderAddress}</p>
            
            <h3>收货人信息</h3>
            <p><strong>姓名:</strong> {savedData.receiverName}</p>
            <p><strong>电话:</strong> {savedData.receiverPhone}</p>
            <p><strong>地址:</strong> {savedData.receiverProvince} {savedData.receiverCity} {savedData.receiverDistrict} {savedData.receiverDetailAddress}</p>
            
            <h3>物品信息</h3>
            <Table 
              columns={columns.filter(col => col.key !== 'operation')}
              dataSource={savedGoods}
              pagination={false}
              bordered
              className="goods-table"
              scroll={{ x: 'max-content' }}
            />
            
            <h3>其他信息</h3>
            <p><strong>重量:</strong> {savedData.weight}KG</p>
            <p><strong>保险:</strong> {savedData.insurance === 'none' ? '无保险' : '基础保险'}</p>
            <p><strong>体积:</strong> {savedData.length}×{savedData.width}×{savedData.height} CM</p>
          </div>
        </Card>
      )}

      {/* 添加物品的弹窗表单 */}
      <Modal
        title="添加物品信息"
        visible={addGoodsModalVisible}
        onOk={handleAddGoodsSubmit}
        onCancel={handleAddGoodsCancel}
        okText="确认添加"
        cancelText="取消"
        width={700}
      >
        <Form
          form={goodsForm}
          layout="vertical"
          name="goods_form"
          initialValues={{
            quantity: 1,
            price: 0
          }}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="货物名称"
                rules={[{ required: true, message: '请输入货物名称' }]}
              >
                <Input placeholder="例如：维生素C" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="specifications"
                label="规格码"
                rules={[{ required: true, message: '请输入规格码' }]}
              >
                <Input placeholder="例如：220粒" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                name="description"
                label="物品描述"
              >
                <Input.TextArea placeholder="请输入物品描述" rows={2} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="quantity"
                label="数量"
                rules={[{ required: true, message: '请输入数量' }]}
              >
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="price"
                label="申报单价(元)"
                rules={[{ required: true, message: '请输入单价' }]}
              >
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default OnlineOrdering;
